/**
 * <pre>
 * Title: 		RayDropFactory.java
 * Project: 	FullNexus4
 * Type:		com.leoly.fullnexus4.utils.RayDropFactory
 * Author:		255507
 * Create:	 	2013-4-11 下午2:51:52
 * Copyright: 	Copyright (c) 2013
 * Company:		
 * <pre>
 */
package com.leoly.fullnexus4.utils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import com.leoly.fullnexus4.R;
import com.leoly.fullnexus4.adaptors.VibratorAdaptor;
import com.leoly.fullnexus4.services.ICallBack;
import com.leoly.fullnexus4.vos.IAppObject;

/**
 * <pre>
 * </pre>
 * 
 * @author 255507
 * @version 1.0, 2013-4-11
 */
public class RayDropFactory {
	private EventHandler handler;

	private Context context;

	private ActivityManager am;

	private VibratorAdaptor vibrator;

	private ICallBack callback;

	private final static Animation animation = new ScaleAnimation(1f, 0.7f, 1f,
			0.7f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
			0.5f);

	public static RayDropFactory getInstance(Context context,
			boolean needVibrate, ICallBack callback, EventHandler handler) {
		RayDropFactory factory = new RayDropFactory();
		factory.context = context;
		factory.handler = handler;
		factory.am = ((ActivityManager) context.getSystemService("activity"));
		factory.vibrator = new VibratorAdaptor(context, needVibrate);
		factory.callback = callback;
		animation.setDuration(100);
		animation.setRepeatCount(1);
		animation.setRepeatMode(AlphaAnimation.REVERSE);
		return factory;
	}

	public ImageView createItem(IAppObject app, int space) {
		final ImageView appIcon = new ImageView(context);
		appIcon.setImageDrawable(app.getIcon());
		appIcon.setPadding(0, space, 0, 0);
		final String pkgName = app.getPkgName();
		appIcon.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fireEvent(appIcon, pkgName, false);
			}
		});

		appIcon.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View arg0) {
				return fireEvent(appIcon, pkgName, true);
			}
		});
		return appIcon;
	}

	private boolean fireEvent(ImageView layout, String pkgName,
			boolean isLongPress) {
		layout.startAnimation(animation);
		// 虚拟按键
		if (pkgName.startsWith(TopConstants.VKEY_PREFIX)) {
			byte btnId = Byte.valueOf(pkgName
					.substring(TopConstants.VKEY_PREFIX.length()));
			switch (btnId) {
			case ButtonFactory.BACK:
				if (isLongPress) {
					doKillAppAction();
				} else {
					doKeyAction(KeyEvent.KEYCODE_BACK);
				}
				break;
			case ButtonFactory.HOME:
				if (isLongPress) {
					doKeyAction(KeyEvent.KEYCODE_POWER);
					if (null != callback) {
						callback.hideAllKeys();
					}
				} else {
					doKeyAction(KeyEvent.KEYCODE_HOME);
				}
				break;
			case ButtonFactory.MENU:
				doKeyAction(KeyEvent.KEYCODE_MENU);
				if (null != callback) {
					callback.hideAllKeys();
				}
				break;
			case ButtonFactory.RECENT:
				if (isLongPress) {
					doKeyAction(KeyEvent.KEYCODE_MENU);
					if (null != callback) {
						callback.hideAllKeys();
					}
				} else {
					doShowRecentApps();
				}
				break;
			case ButtonFactory.POWER:
				if (isLongPress) {
					doLongPressKey(KeyEvent.KEYCODE_POWER);
				} else {
					doKeyAction(KeyEvent.KEYCODE_POWER);
				}
				if (null != callback) {
					callback.hideAllKeys();
				}
				break;
			case ButtonFactory.SEARCH:
				doKeyAction(KeyEvent.KEYCODE_SEARCH);
				break;
			case ButtonFactory.VOLUMN_DOWN:
				doKeyAction(KeyEvent.KEYCODE_VOLUME_DOWN);
				break;
			case ButtonFactory.VOLUMN_UP:
				doKeyAction(KeyEvent.KEYCODE_VOLUME_UP);
				break;
			case ButtonFactory.HIDE:
				if (null != callback) {
					callback.hideAllKeys();
				}
				break;
			default:
				break;
			}
		} else {
			doOpenApplication(pkgName);
		}

		return true;
	}

	private void doKillAppAction() {
		vibrator.vibrator();
		final List<RunningTaskInfo> rti = am.getRunningTasks(1);
		final String cmpName = ((ActivityManager.RunningTaskInfo) rti.get(0)).baseActivity
				.getPackageName();
		String temp = new String(cmpName).toLowerCase();
		// 不杀启动器
		if (temp.contains("launcher") || temp.contains("fullnexus4")) {
			return;
		}
		doKeyAction(KeyEvent.KEYCODE_HOME);
		new Timer().schedule(new TimerTask() {
			public void run() {
				RootContext.getInstance()
						.runCommand("am force-stop " + cmpName);
			}
		}, 1000L);
	}

	private void doKeyAction(int paramInt) {
		handler.sendKeys(paramInt);
		vibrator.vibrator();
	}

	private void doLongPressKey(int paramInt) {
		vibrator.vibrator();
		handler.sendDownTouchKeys(paramInt);
	}

	private void doShowRecentApps() {
		try {
			Class localClass1 = Class.forName("android.os.ServiceManager");
			IBinder localIBinder = (IBinder) localClass1.getMethod(
					"getService", new Class[] { String.class }).invoke(
					localClass1, new Object[] { "statusbar" });
			Class localClass2 = Class.forName(
					"com.android.internal.statusbar.IStatusBarService")
					.getClasses()[0];
			Object localObject = localClass2.getMethod("asInterface",
					new Class[] { IBinder.class }).invoke(null,
					new Object[] { localIBinder });
			localClass2.getMethod("toggleRecentApps", new Class[0]).invoke(
					localObject, new Object[0]);
		} catch (Exception e) {
			doKeyAction(KeyEvent.KEYCODE_APP_SWITCH);
		} finally {
			vibrator.vibrator();
		}
	}

	private void doOpenApplication(String pkgName) {
		pkgName = pkgName.substring(TopConstants.PKG_PREFIX.length());
		Intent intent = context.getPackageManager().getLaunchIntentForPackage(
				pkgName);
		try {
			context.startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(context, context.getString(R.string.canNotRunApp),
					Toast.LENGTH_SHORT);
		}
	}

	private void doHomeKey() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addCategory(Intent.CATEGORY_HOME);
		context.startActivity(intent);
		vibrator.vibrator();
	}
}
